<template>
    <div class="device-tree">
      <SearchFilters @search="loadTree" />
      <DeviceNode
        v-for="item in treeData"
        :key="item.id"
        :node="item"
        @editDevice="onEditDevice"
        @editSpare="onEditSpare"
      /> 
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue'
  import { listSbtz } from '@/api/sbtz/sbtz'
  import SearchFilters from './SearchFilters.vue'
  import DeviceNode from './DeviceNode.vue'
  
  
  const treeData = ref([])
  const loading = ref(false)
  
  async function loadTree(params = {}) {
    loading.value = true
    const { rows = [] } = await listSbtz({
      ...params,
      pageNum: 1,
      pageSize: 1000
    })
  
    // 过滤系统层
    const filtered = rows.filter(r => r.nodeType !== 'SYSTEM')
  
    // 模拟每个设备的备件
    filtered.forEach(d => {
      d.spareInfos = [
        { id: d.id + '-s1', name: '传感器', code: 'SP001', stock: 8 },
        { id: d.id + '-s2', name: '电机', code: 'SP002', stock: 3 }
      ]
    })
  
    // 构建父子结构
    const map = new Map()
    filtered.forEach(f => map.set(f.id, { ...f, children: [] }))
    const roots = []
    filtered.forEach(f => {
      if (!f.parentId || !map.has(f.parentId)) roots.push(map.get(f.id))
      else map.get(f.parentId).children.push(map.get(f.id))
    })
    treeData.value = roots
    loading.value = false
  }
  
  function onEditDevice(device) {
    console.log('编辑设备:', device)
  }
  
  function onEditSpare(spare) {
    console.log('编辑备件:', spare)
  }
  
  onMounted(() => loadTree())
  </script>
  